#include"Seqlist.h"


void SeqlistPrint(SL* ps)
{
	int i=0;
	for(i=0;i<ps->size;i++)
	{
		printf("%d ",ps->a[i]);
	}
	printf("\n");
}
void SeqlistInit(SL* ps)
{
	ps->a=NULL;
	ps->size=ps->capacity=0;
}


void SeqlistDestory(SL* ps)
{
	free(ps->a);
	ps->a=NULL;
	ps->capacity=ps->size=0;
}


void SeqlistCheckCapacity(SL* ps)
{
	if(ps->size==ps->capacity)
	{
		int newcapacity=ps->capacity==0?4:ps->capacity*2;
		SLDataType* tmp=(SLDataType*)realloc(ps->a,newcapacity*sizeof(SLDataType));
		if(tmp==NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a=tmp;
		ps->capacity=newcapacity;
	}
}


void SeqlistPushBack(SL* ps,SLDataType x)
{
	SeqlistCheckCapacity(ps);
	ps->a[ps->size]=x;
	ps->size++;
}
void SeqlistPopBack(SL* ps)
{
	assert(ps->size>0);
	ps->size--;
}
void SeqlistPushFront(SL* ps,SLDataType x)
{
	int end=ps->size-1;
	SeqlistCheckCapacity(ps);
	while(end>=0)
	{
		ps->a[end+1]=ps->a[end];
		end--;
	}
	ps->a[0]=x;
	ps->size++;
}

void SeqlistPopFront(SL* ps)
{
	int begin=1;
	assert(ps->size>0);
	while(begin<ps->size)
	{
		ps->a[begin-1]=ps->a[begin];
		begin++;
	}
	ps->size--;
}


int SeqlistFind(SL* ps,SLDataType x)
{
	int i=0;
	for(i=0;i<ps->size;i++)
	{
		if(ps->a[i]==x)
		{
			return i;
		}
	}
	return -1;
}

void SeqlistInsert(SL* ps,int pos,SLDataType x)
{
	int end=ps->size-1;
	assert(pos>=0&&pos<=ps->size);
	SeqlistCheckCapacity(ps);
	while(end>=pos)
	{
		ps->a[end+1]=ps->a[end];
		end--;
	}
	ps->a[pos]=x;
	ps->size++;
	
}



void SeqlistErase(SL* ps,int pos)
{
	int begin=pos+1;
	assert(pos>=0&&pos<ps->size);
	while(begin<ps->size)
	{
		ps->a[begin-1]=ps->a[begin];
		begin++;
	} 
	ps->size--;
}



